const jwt = require('jsonwebtoken')

const { JWT_SECURE } = require('../config/config_deafault')
const { invlidToken, TokenExpiredError, } = require('../constant/tokenErrortype')


//jwt存放信息
const auth = async (ctx, next) => {
    const { authorization = '' } = ctx.request.header
    const token = authorization.replace('Bearer ', '')
    try {
        const user = jwt.verify(token, JWT_SECURE)
        ctx.state.user = user
    }
    catch (error) {
        switch (error.name) {
            case 'TokenExpiredError':
                console.error('token已过期', error);
                return ctx.app.emit('error', TokenExpiredError, ctx)
            case 'JsonWebTokenError':
                console.error('无效的token', error);
                ctx.app.emit('error', invlidToken, ctx)
                return
        }
    }
    await next()
}

//是否管理员权限
// const handAdminPermission = async (ctx, next) => {
//     const { IsAdmin } = ctx.state.user

//     if (!IsAdmin) {
//         console.error('该用户没有管理员权限');
//         return ctx.app.emit('error', handNotAdminPermission, ctx)
//     }
//     await next();
// }

//校验jwt
const authCheck = async (authorization) => {
    const token = authorization.replace('Bearer ', '')
    try {
        const user = jwt.verify(token, JWT_SECURE)
        return user.user_id
    }
    catch (error) {
        switch (error.name) {
            case 'TokenExpiredError':
                throw new Error('token已过期')
            case 'JsonWebTokenError':
                throw new Error('无效的token')
        }
    }
}


module.exports = { auth, authCheck }